
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import Controlador.ControlImagen;
import Controlador.ControlProdServ;
import Controlador.ControlProveedor;
import Modelo.Imagen;
import Modelo.Producto;
import Modelo.Proveedor;
import Modelo.Servicio;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowStateListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Damian
 */
public class VisualizarProdServ extends javax.swing.JFrame {

    /**
     * Creates new form VisualizarProdServ
     */
    ControlProveedor controlp = new ControlProveedor();
    ArrayList<Proveedor> l;
    TableRowSorter<TableModel> rs, rs1;
    SeleccionarImagen ven;
    HashMap<String, ImageIcon> lImg;
    ArrayList<Producto> lista;
    //final Integer codImg = -1;

    public VisualizarProdServ() {
        initComponents();
        setIconImage(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/Vista/Iconos/Publicont.png")));
        try {
            l = controlp.listar();
        } catch (SQLException ex) {
            Logger.getLogger(VisualizarProdServ.class.getName()).log(Level.SEVERE, null, ex);
        }
        tablaProd.setModel(modeloProductos());
        tablaServ.setModel(modeloServicios());

        rs = new TableRowSorter<>(tablaProd.getModel());
        tablaProd.setRowSorter(rs);

        tablaProd.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    colocarImg();
                }
            }
        });

        rs1 = new TableRowSorter<>(tablaServ.getModel());
        tablaServ.setRowSorter(rs1);

        txtBuscar.getDocument().addDocumentListener(
                new DocumentListener() {
                    public void changedUpdate(DocumentEvent e) {
                        filtrar();
                    }

                    public void insertUpdate(DocumentEvent e) {
                        filtrar();
                    }

                    public void removeUpdate(DocumentEvent e) {
                        filtrar();
                    }
                });
        txtBuscarServ.getDocument().addDocumentListener(
                new DocumentListener() {
                    public void changedUpdate(DocumentEvent e) {
                        filtrarServ();
                    }

                    public void insertUpdate(DocumentEvent e) {
                        filtrarServ();
                    }

                    public void removeUpdate(DocumentEvent e) {
                        filtrarServ();
                    }
                });
    }

    private void colocarImg() {
        try {
            String i = codigoSeleccionado();
            String codima = null;
            for (int j = 0; j < lista.size(); j++) {
                Producto prod = lista.get(j);
                if (prod.getCodigo().equals(i)) {
                    codima = prod.getCodImg();
                }
            }
            if (lImg != null) {
                lblImg.setIcon(lImg.get(codima));
            }
        } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) {
        }
    }

    //<editor-fold defaultstate="collapsed" desc="Renderer">
    class Renderer extends DefaultTableCellRenderer {

        public void fillColor(JTable t, JLabel l, boolean isSelected) {
            //setting the background and foreground when JLabel is selected
            if (isSelected) {
                l.setBackground(t.getSelectionBackground());
                l.setForeground(t.getSelectionForeground());
            } else {
                l.setBackground(t.getBackground());
                l.setForeground(t.getForeground());
            }

        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {

            if (value instanceof JLabel) {
                JLabel label = (JLabel) value;
                //to make label foreground n background visible you need to
                // setOpaque -> true
                label.setOpaque(true);
                fillColor(table, label, isSelected);
                return label;

            } else {
                return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            }
        }

    }
//</editor-fold>

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaProd = new javax.swing.JTable();
        jToolBar1 = new javax.swing.JToolBar();
        btnAgregarProd = new javax.swing.JButton();
        btnEliminarProd = new javax.swing.JButton();
        btnEditarProd = new javax.swing.JButton();
        btnRefrescarProd = new javax.swing.JButton();
        btnImportar = new javax.swing.JButton();
        btnImg = new javax.swing.JButton();
        filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(100, 0), new java.awt.Dimension(100, 0), new java.awt.Dimension(200, 32767));
        jLabel1 = new javax.swing.JLabel();
        txtBuscar = new org.jdesktop.swingx.JXSearchField();
        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        filler3 = new javax.swing.Box.Filler(new java.awt.Dimension(100, 0), new java.awt.Dimension(100, 0), new java.awt.Dimension(100, 32767));
        lblImg = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tablaServ = new javax.swing.JTable();
        jToolBar2 = new javax.swing.JToolBar();
        btnAgregarServ = new javax.swing.JButton();
        btnEliminarServ = new javax.swing.JButton();
        btnEditarServ = new javax.swing.JButton();
        btnRefrescarServ = new javax.swing.JButton();
        filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(200, 0), new java.awt.Dimension(200, 0), new java.awt.Dimension(200, 32767));
        jLabel2 = new javax.swing.JLabel();
        txtBuscarServ = new org.jdesktop.swingx.JXSearchField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Productos y Servicios");
        setMinimumSize(new java.awt.Dimension(300, 82));

        jPanel2.setLayout(new java.awt.BorderLayout(5, 5));

        tablaProd.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tablaProd.setName(""); // NOI18N
        tablaProd.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        jScrollPane1.setViewportView(tablaProd);

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jToolBar1.setRollover(true);
        jToolBar1.setMargin(new java.awt.Insets(5, 0, 5, 0));

        btnAgregarProd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/list-add.png"))); // NOI18N
        btnAgregarProd.setToolTipText("Agregar");
        btnAgregarProd.setFocusable(false);
        btnAgregarProd.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAgregarProd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAgregarProd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarProdActionPerformed(evt);
            }
        });
        jToolBar1.add(btnAgregarProd);

        btnEliminarProd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/list-remove.png"))); // NOI18N
        btnEliminarProd.setToolTipText("Eliminar");
        btnEliminarProd.setFocusable(false);
        btnEliminarProd.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEliminarProd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEliminarProd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarProdActionPerformed(evt);
            }
        });
        jToolBar1.add(btnEliminarProd);

        btnEditarProd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/view-form.png"))); // NOI18N
        btnEditarProd.setToolTipText("Editar");
        btnEditarProd.setFocusable(false);
        btnEditarProd.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEditarProd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEditarProd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarProdActionPerformed(evt);
            }
        });
        jToolBar1.add(btnEditarProd);

        btnRefrescarProd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/view-refresh.png"))); // NOI18N
        btnRefrescarProd.setToolTipText("Refrescar");
        btnRefrescarProd.setFocusable(false);
        btnRefrescarProd.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnRefrescarProd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnRefrescarProd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefrescarProdActionPerformed(evt);
            }
        });
        jToolBar1.add(btnRefrescarProd);

        btnImportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/import.png"))); // NOI18N
        btnImportar.setToolTipText("Importar Desde Excel");
        btnImportar.setFocusable(false);
        btnImportar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnImportar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnImportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnImportar);

        btnImg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/image-x-generic.png"))); // NOI18N
        btnImg.setToolTipText("Seleccionar Imagen");
        btnImg.setFocusable(false);
        btnImg.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnImg.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnImg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImgActionPerformed(evt);
            }
        });
        jToolBar1.add(btnImg);
        jToolBar1.add(filler1);

        jLabel1.setText("Filtro:  ");
        jToolBar1.add(jLabel1);
        jToolBar1.add(txtBuscar);

        jPanel2.add(jToolBar1, java.awt.BorderLayout.PAGE_START);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jLabel3.setText("Imagen");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(lblImg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(filler3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(filler3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(lblImg, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(254, Short.MAX_VALUE))
        );

        jPanel2.add(jPanel1, java.awt.BorderLayout.LINE_END);

        jTabbedPane1.addTab("Productos", jPanel2);

        jPanel3.setLayout(new java.awt.BorderLayout());

        tablaServ.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tablaServ.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(tablaServ);

        jPanel3.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jToolBar2.setRollover(true);

        btnAgregarServ.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/list-add.png"))); // NOI18N
        btnAgregarServ.setToolTipText("Agregar");
        btnAgregarServ.setFocusable(false);
        btnAgregarServ.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAgregarServ.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAgregarServ.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarServActionPerformed(evt);
            }
        });
        jToolBar2.add(btnAgregarServ);

        btnEliminarServ.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/list-remove.png"))); // NOI18N
        btnEliminarServ.setToolTipText("Eliminar");
        btnEliminarServ.setFocusable(false);
        btnEliminarServ.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEliminarServ.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEliminarServ.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarServActionPerformed(evt);
            }
        });
        jToolBar2.add(btnEliminarServ);

        btnEditarServ.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/view-form.png"))); // NOI18N
        btnEditarServ.setToolTipText("Editar");
        btnEditarServ.setFocusable(false);
        btnEditarServ.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEditarServ.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEditarServ.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarServActionPerformed(evt);
            }
        });
        jToolBar2.add(btnEditarServ);

        btnRefrescarServ.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/view-refresh.png"))); // NOI18N
        btnRefrescarServ.setToolTipText("Refrescar");
        btnRefrescarServ.setFocusable(false);
        btnRefrescarServ.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnRefrescarServ.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnRefrescarServ.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefrescarServActionPerformed(evt);
            }
        });
        jToolBar2.add(btnRefrescarServ);
        jToolBar2.add(filler2);

        jLabel2.setText("Filtro:  ");
        jToolBar2.add(jLabel2);
        jToolBar2.add(txtBuscarServ);

        jPanel3.add(jToolBar2, java.awt.BorderLayout.PAGE_START);

        jTabbedPane1.addTab("Servicios", jPanel3);

        getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnRefrescarServActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefrescarServActionPerformed
        actualizarServ();
    }//GEN-LAST:event_btnRefrescarServActionPerformed
    private void filtrar() {
        RowFilter<TableModel, Object> rf = null;
        try {
            rf = RowFilter.regexFilter(("(?i)") + txtBuscar.getText(), 1, 2, 5);
        } catch (java.util.regex.PatternSyntaxException e) {
        }
        rs.setRowFilter(rf);
    }

    private void filtrarServ() {
        RowFilter<TableModel, Object> rf = null;
        try {
            rf = RowFilter.regexFilter(("(?i)") + txtBuscarServ.getText(), 1, 2);
        } catch (java.util.regex.PatternSyntaxException e) {
        }
        rs1.setRowFilter(rf);
    }
    private void btnRefrescarProdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefrescarProdActionPerformed
        actualizarProd();

    }//GEN-LAST:event_btnRefrescarProdActionPerformed

    private String codigoSeleccionado() throws ArrayIndexOutOfBoundsException{
        String cod = "";
        int i = tablaProd.getSelectedRow();
        if (i>=0) {
            i = rs.convertRowIndexToModel(i);
            cod = ((JLabel) (((DefaultTableModel) tablaProd.getModel()).getValueAt(i, 0))).getText();
        }
        return cod;
    }
    private void btnEliminarProdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarProdActionPerformed
        ControlProdServ control = new ControlProdServ();
        DefaultTableModel model = ((DefaultTableModel) tablaProd.getModel());
        int i = tablaProd.getSelectedRow();
        
        if (i >= 0) {
            i = rs.convertRowIndexToModel(i);
            int cod = Integer.parseInt(codigoSeleccionado());
            System.out.println("Eliminar el producto: " + cod);
            control.eliminarProd(cod);
            actualizarProd();
        } else {
            JOptionPane.showMessageDialog(rootPane, "Seleccione un producto de la tabla para eliminar");
        }
    }//GEN-LAST:event_btnEliminarProdActionPerformed

    private void btnEliminarServActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarServActionPerformed
        ControlProdServ control = new ControlProdServ();
        DefaultTableModel model = ((DefaultTableModel) tablaServ.getModel());
        int i = tablaServ.getSelectedRow();
        i = rs.convertRowIndexToModel(i);
        if (i >= 0) {
            int cod = Integer.parseInt(model.getValueAt(i, 0).toString());
            System.out.println("Eliminar el servicio: " + cod);
            control.eliminarServ(cod);
            actualizarServ();
        } else {
            JOptionPane.showMessageDialog(rootPane, "Seleccione un servicio de la tabla para eliminar");
        }
    }//GEN-LAST:event_btnEliminarServActionPerformed

    private void btnAgregarServActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarServActionPerformed
        RegistrarServicio ven = new RegistrarServicio();
        ven.setVisible(true);
        ven.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                actualizarServ();
            }
        });
    }//GEN-LAST:event_btnAgregarServActionPerformed

    private void btnAgregarProdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarProdActionPerformed
        RegistrarProd ven = new RegistrarProd();
        ven.setVisible(true);
        ven.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                actualizarProd();
            }
        });
    }//GEN-LAST:event_btnAgregarProdActionPerformed

    private void btnEditarProdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarProdActionPerformed
        ControlProdServ control = new ControlProdServ();
        DefaultTableModel model = ((DefaultTableModel) tablaProd.getModel());

        int i = tablaProd.getSelectedRow();
        
        if (i >= 0) {
            i = rs.convertRowIndexToModel(i);
            Integer cod = Integer.parseInt(codigoSeleccionado());
            String prov = model.getValueAt(i, 5).toString();
            String proveedor[] = prov.split("-");

            Producto prod = new Producto(cod.toString(),
                    model.getValueAt(i, 1).toString(),
                    model.getValueAt(i, 2).toString(),
                    Float.parseFloat(model.getValueAt(i, 3).toString()),
                    Integer.parseInt(model.getValueAt(i, 4).toString()),
                    proveedor[0]);

            ModificarProd ven = new ModificarProd(prod);
            ven.setVisible(true);
            ven.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosed(WindowEvent e) {
                    actualizarProd();
                }
            });

        } else {
            JOptionPane.showMessageDialog(rootPane, "Seleccione un producto de la tabla para modificar");
        }
    }//GEN-LAST:event_btnEditarProdActionPerformed

    private void btnEditarServActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarServActionPerformed
        ControlProdServ control = new ControlProdServ();
        DefaultTableModel model = ((DefaultTableModel) tablaServ.getModel());
        int i = tablaServ.getSelectedRow();
        i = rs.convertRowIndexToModel(i);
        if (i >= 0) {
            Integer cod = Integer.parseInt(model.getValueAt(i, 0).toString());
            Servicio serv = new Servicio(cod.toString(),
                    model.getValueAt(i, 1).toString(),
                    model.getValueAt(i, 2).toString(),
                    Float.parseFloat(model.getValueAt(i, 3).toString()));

            ModificarServ ven = new ModificarServ(serv);
            ven.setVisible(true);
            ven.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosed(WindowEvent e) {
                    actualizarServ();
                }
            });

        } else {
            JOptionPane.showMessageDialog(rootPane, "Seleccione un Servicio de la tabla para modificar");
        }
    }//GEN-LAST:event_btnEditarServActionPerformed

    private void btnImportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImportarActionPerformed
        Importar ven = new Importar();
        ven.setVisible(true);
    }//GEN-LAST:event_btnImportarActionPerformed

    private void btnImgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImgActionPerformed
        int i = tablaProd.getSelectedRow();
        //final String codImg="";
        i = rs.convertRowIndexToModel(i);

        if (i >= 0) {

            ven = new SeleccionarImagen(Integer.parseInt(((JLabel) (((DefaultTableModel) tablaProd.getModel()).getValueAt(i, 0))).getText()));

            ven.addWindowListener(new WindowAdapter() {

                @Override
                public void windowClosed(WindowEvent e) {
                    super.windowClosed(e); //To change body of generated methods, choose Tools | Templates.
                    //System.out.println(codImg);
                    actualizarProd();
                }

                @Override
                public void windowClosing(WindowEvent e) {
                    System.out.println("qwe");
                    super.windowClosing(e); //To change body of generated methods, choose Tools | Templates.
                    System.out.println("asd");
                }

            });

            ven.setVisible(true);
            ven.setLocationRelativeTo(null);
        } else {
            JOptionPane.showMessageDialog(rootPane, "Seleccione un producto de la tabla");
        }
    }//GEN-LAST:event_btnImgActionPerformed

    private void actualizarProd() {
        tablaProd.setRowSorter(null);
        rs = null;
        tablaProd.setModel(modeloProductos());
        rs = new TableRowSorter<>(tablaProd.getModel());
        tablaProd.setRowSorter(rs);
        filtrar();
        colocarImg();
    }

    private void actualizarServ() {
        tablaServ.setRowSorter(null);
        rs1 = null;
        tablaServ.setModel(modeloServicios());
        rs1 = new TableRowSorter<>(tablaServ.getModel());

        tablaServ.setRowSorter(rs1);
        filtrarServ();

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VisualizarProdServ.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VisualizarProdServ.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VisualizarProdServ.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VisualizarProdServ.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VisualizarProdServ().setVisible(true);
            }
        });
    }

    public DefaultTableModel modeloServicios() {
        String[] columnas = {"Código", "Nombre", "Descripción", "Precio"};
        DefaultTableModel tabla = new DefaultTableModel(columnas, 0);
        ArrayList<Servicio> lista = new ControlProdServ().listarServicios();
        for (int i = 0; i < lista.size(); i++) {
            Servicio ser = lista.get(i);
            tabla.addRow(new Object[]{ser.getCodigo(), ser.getNombre(),
                ser.getDescripcion(), ser.getPrecio()});
        }
        return tabla;
    }

    public DefaultTableModel modeloProductos() {
        String[] columnas = {"Código", "Nombre", "Descripción", "Precio", "Stock", "Proveedor"};
        DefaultTableModel tabla = new DefaultTableModel(columnas, 0) {
            @Override

            public Class getColumnClass(int columnIndex) {
                if (columnIndex == 0) {
                    return getValueAt(0, columnIndex).getClass();
                } else {
                    return super.getColumnClass(columnIndex);
                }

            }

            @Override
            public boolean isCellEditable(int row, int column) {
                return false; //To change body of generated methods, choose Tools | Templates.
            }

        };
        lista = new ControlProdServ().listarProductos();
        System.out.println("Lista prod:" + lista.size());
        ControlImagen cimg = new ControlImagen();
        HashMap<String, ImageIcon> map = new HashMap<>();
        tablaProd.setDefaultRenderer(JLabel.class, new Renderer());
        ArrayList<JLabel> listLbl = new ArrayList<>();
        try {
            ArrayList<Imagen> listImg = (cimg).getImagenes();
            System.out.println("Imagenes: " + listImg.size());
            lImg = new HashMap<>();

            for (int i = 0; i < listImg.size(); i++) {
                Imagen imagen = listImg.get(i);
                map.put(imagen.getCod(),
                        new ImageIcon(cimg.redimensionar(imagen.getImagen(), 22, 22)));
                lImg.put(imagen.getCod(),
                        new ImageIcon(cimg.redimensionar(imagen.getImagen(), lblImg.getWidth(), lblImg.getHeight())));
            }
            System.out.println("map: " + map.size());
            System.out.println(map);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        for (int i = 0; i < lista.size(); i++) {
            Producto prod = lista.get(i);
            JLabel lbl = new JLabel(prod.getCodigo());
            lbl.setIcon(map.get(prod.getCodImg()));
            listLbl.add(lbl);
            System.out.println(lbl.getText() + " " + prod.getCodImg());
            tabla.addRow(new Object[]{lbl, prod.getNombre(),
                prod.getDescripcion(), prod.getPrecioUnitario(),
                prod.getStock(), proveedorMostrar(prod.getCodProveedor())});
        }
        return tabla;
    }

    public String proveedorMostrar(String cod) {
        String r = "";

        for (int i = 0; i < l.size(); i++) {
            Proveedor proveedor = l.get(i);
            if (proveedor.getCodigo().equals(cod)) {
                r = cod + "-" + proveedor.getEmpresa();
                break;
            }
        }

        return r;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregarProd;
    private javax.swing.JButton btnAgregarServ;
    private javax.swing.JButton btnEditarProd;
    private javax.swing.JButton btnEditarServ;
    private javax.swing.JButton btnEliminarProd;
    private javax.swing.JButton btnEliminarServ;
    private javax.swing.JButton btnImg;
    private javax.swing.JButton btnImportar;
    private javax.swing.JButton btnRefrescarProd;
    private javax.swing.JButton btnRefrescarServ;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.Box.Filler filler1;
    private javax.swing.Box.Filler filler2;
    private javax.swing.Box.Filler filler3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JLabel lblImg;
    private javax.swing.JTable tablaProd;
    private javax.swing.JTable tablaServ;
    private org.jdesktop.swingx.JXSearchField txtBuscar;
    private org.jdesktop.swingx.JXSearchField txtBuscarServ;
    // End of variables declaration//GEN-END:variables
}
